﻿/*******************************************************************************************************
 * 
 * http://stackoverflow.com/questions/263551/databind-the-source-property-of-the-webbrowser-in-wpf
 * 
 * 
 ********************************************************************************************************/


using System;
using System.Windows;
using System.Windows.Controls;

namespace RSSFeedReader.AttachedProperties
{
    /// <summary>
    /// Helper class to allowing binding of the source property
    /// through attached property.
    /// </summary>
    public static class WebBrowserUtility
    {
        /// <summary>
        /// Register the attached property.
        /// </summary>
        public static readonly DependencyProperty BindableSourceProperty =
            DependencyProperty.RegisterAttached(
            "BindableSource",
            typeof(string),
            typeof(WebBrowserUtility),
            new UIPropertyMetadata(null, BindableSourcePropertyChanged));

        /// <summary>
        /// Gets the BindableSourceProperty.
        /// </summary>
        /// <param name="obj">The object to get the BindableSourceProperty of.</param>
        /// <returns>String value of the source.</returns>
        public static string GetBindableSource(DependencyObject obj)
        {
            return (string)obj.GetValue(BindableSourceProperty);
        }

        /// <summary>
        /// Sets the bindable source.
        /// </summary>
        /// <param name="obj">The object to set the bindable source.</param>
        /// <param name="value">The value to set.</param>
        public static void SetBindableSource(DependencyObject obj, string value)
        {
            obj.SetValue(BindableSourceProperty, value);
        }

        /// <summary>
        /// Occurs when the BindableSourceProperty changes.
        /// </summary>
        /// <param name="dp">The BindableSourceProperty.</param>
        /// <param name="e">The new property.</param>
        public static void BindableSourcePropertyChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
        {
            WebBrowser browser = dp as WebBrowser;
            if (browser != null)
            {
                if (e.NewValue != null && e.NewValue != e.OldValue)
                {
                    browser.Visibility = Visibility.Visible;
                    string uri = e.NewValue as string;
                    Uri newUri = new Uri(uri, UriKind.Absolute);
                    browser.Source = newUri;
                    return;
                }
                browser.Visibility = Visibility.Hidden;
            }
        }
    }
}
